package com.manager.base.interceptor;

/**
 * Created by apple on 2018/2/20.
 */
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by vic wu on 2015/8/26.
 *
 * spring-dispatcher.xml中定义,获取页面传过来的token,设置进session ,没有则不设置 .
 *
 * 区别：
 * AuthInterceptor　对权限进行验证
 * SessionInterceptor 不验证权限,只设置当前session到ThreadLocal
 *
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(SessionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if(request.getRequestURI().endsWith("heartBeat")){//heartBeat不设置token
                return true;
            }
            long current = System.currentTimeMillis();

//            SessionUtil.removeSession();

//        if(SessionUtil.getSession() != null ) return super.preHandle(request, response, handler);

            String token = request.getParameter("token");
            String imei = request.getParameter("imei");
            String version = request.getParameter("version");
            String client = request.getParameter("client");
            String openId = null ;

            /**
             * 如果不存在从cookie中获取 , 用于web网站中的
             */
            //if (StringUtils.isBlank(token) || StringUtils.isBlank(imei)) {
            Cookie[] cookies = request.getCookies();

            if( cookies != null && cookies.length > 0 ) {

                for (Cookie cookie : cookies) {
                    if (cookie.getName().equalsIgnoreCase("pin") && StringUtils.isBlank(token)) {
                        token = cookie.getValue();
                    }
                    if (cookie.getName().equalsIgnoreCase("imei") && StringUtils.isBlank(imei)) {
                        imei = cookie.getValue();
                    }

                    if ( cookie.getName().equalsIgnoreCase("openId") ) {       //openId从客户端获取，没做分布式session
                        openId = cookie.getValue();
                        if( StringUtils.isNotEmpty( openId )) {
                            request.getSession().setAttribute("openId", openId );
                        }
                    }
                }
            }
            //}

//            logger.info("session　解析参数 {}ms ", System.currentTimeMillis() - current);

            if( StringUtils.isBlank(token) )
                token = (String)request.getSession().getAttribute("token" )  ;

            if (StringUtils.isBlank(token) ) {

            } else {
                try {
//                    SessionUtil.setToken(token);
                } catch (Exception e) {
                }
            }
//            logger.info("session　验证token耗时 {}ms ", System.currentTimeMillis() - current);

            long cost = System.currentTimeMillis() - current;
            logger.info("session 添加总耗时 {}ms ", cost);

        }catch (Exception e ){
            logger.error( "解析session出错" , e );
        }
        return super.preHandle(request, response, handler);
    }

}
